import pandas  as pd
from Version3.utils import *
clinic_save_path = opj(base_path,'data','original_data','Clinic')
# 读取数据
patient_data = pd.read_csv(opj(clinic_save_path,'patient-clinical-data.csv'))


# 编码
encoding_maps = {
    'Tumour Type': {
        'Other type': 0,
        'Invasive ductal carcinoma': 1,
        'Invasive lobular carcinoma': 2
    },
    'ER': {
        'Positive': 1,
        'Negative': 0
    },
    'PR': {
        'Positive': 1,
        'Negative': 0
    },
    'HER2': {
        'Positive': 1,
        'Negative': 0
    },
    'HER2 Expression': {
        '0': 0,
        '1+': 1,
        '2+': 2,
        '3+': 3
    },
    'Molecular subtype': {
        'Luminal A': 0,
        'Luminal B': 1,
        'HER2(+)': 2,
        'Triple negative': 3,
    },
        'Surgical': {
        'Axillary lymph node dissection': 0,
            'Sentinel lymph node biopsy': 1
    },
    'ALN status': {
        'N0': 0,
        'N+(1-2)': 1,
        'N+(>2)': 1
    }
}

    
# 对每一列应用对应的 map() 并直接修改原列
for column, mapping in encoding_maps.items():
    patient_data[column] = patient_data[column].map(mapping)

# 提取">数字"和"<数字"部分并进行处理
def handle_gt_lt(value):
    if isinstance(value, str):
        if '＞' in value:
            return ('>', round(float(value[1:-1])*0.01,2))  # 提取'>'后的数字
        elif '＜' in value:
            return ('<', round(float(value[1:-1])*0.01,2))  # 提取'<'后的数字
    return (None, None)

# 将">数字"和"<数字"字符串转为浮动数值及其对应类型
patient_data['Ki67_gt_lt'], patient_data['Ki67_value'] = zip(*patient_data['Ki67'].apply(handle_gt_lt))
# 确保不会在`None`值的情况下进行操作
gt_ranges = patient_data[patient_data['Ki67_gt_lt'].apply(lambda x: x == '>' if x is not None else False)]['Ki67_value'].unique()
lt_ranges = patient_data[patient_data['Ki67_gt_lt'].apply(lambda x: x == '<' if x is not None else False)]['Ki67_value'].unique()

# 计算大于某个值的所有数据的平均值
mean_values_gt = {r: float(patient_data[patient_data['Ki67_value'] > r]['Ki67_value'].mean()) for r in gt_ranges}

# 计算小于某个值的平均值
mean_values_lt = {r: patient_data[patient_data['Ki67_value'] < r]['Ki67_value'].mean() for r in lt_ranges}
# 动态替换">数字"和"<数字"为对应的平均值
def replace_gt_lt(value, gt_mean_values, lt_mean_values):
    if isinstance(value, str):
        if  '＞' in value:
            range_value =  round(float(value[1:-1])*0.01,2)
            return round(range_value,2)  if pd.isna(gt_mean_values.get(range_value, value)) else round(gt_mean_values.get(range_value, value),2)
        elif '＜' in value:
            range_value =  round(float(value[1:-1])*0.01,2)
            return round(range_value,2) if pd.isna(lt_mean_values.get(range_value, value)) else round(lt_mean_values.get(range_value, value),2)
        elif '-' in value:
            lower, upper = value.split('-')
            upper = upper.replace('%','')
            lower = float(lower)*0.01
            upper = float(upper)*0.01
            # 可以根据需要进行处理，例：将范围的中值作为该范围的代表
            return (round((lower + upper) / 2, 2))
    return value

# 替换Ki67列的值
patient_data['Ki67'] = patient_data['Ki67'].apply(lambda x: replace_gt_lt(x, mean_values_gt, mean_values_lt))

# 将Ki67列转为数字类型，确保非'>'和'<'的数字数据也被正确处理
patient_data['Ki67'] = pd.to_numeric(patient_data['Ki67'], errors='coerce')



# 删除部分列
columns_to_drop = [
                   'Unnamed: 0', # 起始列
                   'Histological grading',# 组织学分级 有缺失值
                   'Ki67_gt_lt', # 中间列
                   'Ki67_value',
                #    'Age(years)',
                #    'Tumour Size(cm)',
                #    'Tumour Type',
                #    'Surgical',
                #    'Molecular subtype',
                   'Number of lymph node metastases',
                #    'Ki67'
                   ]
patient_data =  patient_data.drop(columns=columns_to_drop)


patient_data.to_csv(opj(clinic_save_path,'clinic_data.csv'),index=False)